<?php 
namespace Admin\Controller;
use Think\Page;
class ApiController extends AdminController {

	function index($p = 1){
        $this->assign('_list',$this->lists('Movies'));
		$this->display();
	}


	/**
	 * 电影院信息
	 */
	function theater(){
		$this->assign('_list',$this->lists('Cinema'));
		$this->display();
	}
	
	/**
	 * 电影院管理
	 */
	function manage($p=1){
		//id start_time end_time cid mid price 


		$res = M('Manage')->alias('m')
				->field('m.*,r.name,mv.title,c.title AS t')
				->join('LEFT JOIN api_cinema_rooms AS r ON r.id = m.rid')
				->join('LEFT JOIN api_movies AS mv ON mv.id = m.mid')
				->join('LEFT JOIN api_cinema AS c ON c.id = m.cid')
				->limit(($p-1)*50,50)
				->order('m.start_time asc ,mv.id desc')
				->select();
		
		$page = new Page( M('Manage')->count(),50);
		$this->assign('page',$page->show());
		$this->assign('list',$res);
		$this->display();
	}


	/**
	 * 增加API
	 * @$param type 
	 * @$param model 
	 */
	function add($model = 'Movies'){
		if(IS_POST)
		{
			if(M($model)->create())
			{
				M($model)->add();
				$this->success('新增成功');
			}
		}
		$this->display();
	}

	/**
	 * 删除API
	 * @return [type] [description]
	 */
	function delete(){
		$ids = I('post.ids');
		$ids = implode(',', $ids);
		//$map = array("id"=>array("in",$ids));
		M('Movies')->where(1)->delete();
		 $this->success('删除成功');
	} 

	/**
	 * 设备信息 
	 */
	function setManage($max = 20){
		   $cids = M('Cinema')->field('id')->select();
	    $movies = M('Movies')->field('id')->select();
	    $times = M('Times')->select();
	    //添加 80 天的放映


		foreach($cids as $k=>$v)
		{	
			//查找该电影院的厅  
			$ciname = M('CinemaRooms')->where('cinema_id='.$v['id'])->select();
			foreach($ciname as $m=>$n)
			{
				for($i = 0 ; $i < $max ; $i ++)
				{
					foreach($times as $q => $w)
					{
						$data = array();
						$data['start_time'] = strtotime(date('Y-m-d')) + $w['start_time'] + $i * 24 * 60 * 60 ; 
						$data['end_time'] = strtotime(date('Y-m-d')) + $w['start_time'] + $i * 24 * 60 * 60 + 2*60*60 ;  
						$data['cid'] = $v['id'];
						$data['mid'] = $movies[mt_rand(0,count($movies))]['id'];
						$data['rid'] = $n['id'];
						$data['price'] = mt_rand(17.5,70);
						M('Manage')->add($data);
					}
					
				}
				
			}
		}

		// $res = M('Manage')->alias('m')
		// 		->field('m.*,r.name,mv.title,c.title AS t')
		// 		->join('LEFT JOIN api_cinema_rooms AS r ON r.id = m.rid')
		// 		->join('LEFT JOIN api_movies AS mv ON mv.id = m.mid')
		// 		->join('LEFT JOIN api_cinema AS c ON c.id = m.cid')
		// 		->limit(0,50)
		// 		->select();
	}
	
}
